﻿using System;
using System.Collections;
using Castle.Core;
using Castle.MicroKernel;

namespace MetaContainer.Castle
{
   /// <summary>
   /// Provides common method used throughout the assembly.
   /// </summary>
   internal static class Common
   {
      /// <summary>
      /// Registers factory method mapping in Castle kernel.
      /// </summary>
      /// <param name="kernel">Kernel in which method should be registered.</param>
      /// <param name="from">Service interface type.</param>
      /// <param name="factoryMethod">A method producing service implementations.</param>      
      /// <param name="scope">Scope/lifestyle of registration.</param>
      internal static void RegisterInKernel(IKernel kernel, Type from, Func<string, object> factoryMethod, Scope scope)
      {
         IDictionary properties = new Hashtable();
         properties["factoryMethod"] = factoryMethod;
         
         ComponentModel serviceModel = kernel.ComponentModelBuilder.BuildModel(
            Guid.NewGuid().ToString(), from, from, properties);

         serviceModel.LifestyleType = scope == Scope.Transient ? LifestyleType.Transient : LifestyleType.Singleton;

         serviceModel.CustomComponentActivator = typeof(FactoryMethodActivator);

         kernel.AddCustomComponent(serviceModel);
      }
      /// <summary>
      /// Maps MetaContainer scope representation (<see cref="Scope"/>) to Castle's lifestyle (<see cref="LifestyleType"/>).
      /// </summary>
      /// <param name="scope">Lifestyle/scope in MetaContainer's terms.</param>
      /// <returns>Lifestyle/scope in Castle's terms.</returns>
      internal static LifestyleType MapLifestyle(Scope scope)
      {
         return scope == Scope.Transient ? LifestyleType.Transient : LifestyleType.Singleton;
      }
   }
}
